<template>
  <div class="params">
    <div class="navigation">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      ></el-alert>

      <div class="select-box">
        <span class="title">选择商品分类：</span>
        <el-cascader
          :options="categoryList"
          :props="levelProps"
          expand-trigger="hover"
          @change="selectCate"
          v-model="selectedKeys"
        ></el-cascader>
      </div>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
            <el-button
              class="add-btn"
              type="primary"
              size="small"
              :disabled="selectedKeys.length !== 3"
              @click="addDialogVisible = true"
            >
              添加参数
            </el-button>

          <template>
            <el-table :data="manyList" style="width: 100%" border>
              <el-table-column type="expand">
                <!-- <div class="tags-box"> -->
                <template slot-scope="scope">
                  <el-tag
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index, scope.row)"
                    v-for="(item, index) in scope.row.attr_vals"
                    :key="index"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </template>
                <!-- </div> -->
              </el-table-column>
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-row class="btns">
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      @click="showEditDialog(scope.row.attr_id)"
                      >编辑</el-button
                    >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      @click="deleteDialog(scope.row.attr_id)"
                      >删除</el-button
                    >
                  </el-row>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">
          
            <el-button
              class="add-btn"
              type="primary"
              size="small"
              :disabled="selectedKeys.length !== 3"
              @click="addDialogVisible = true"
            >
              添加属性
            </el-button>

          <el-table :data="onlyList" style="width: 100%" border>
            <el-table-column type="expand">
              <!-- <div class="tags-box"> -->
              <template slot-scope="scope">
                <el-tag
                  closable
                  :disable-transitions="false"
                  @close="handleClose(index, scope.row)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
              <!-- </div> -->
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-row class="btns">
                  <el-button
                    type="primary"
                    icon="el-icon-edit"
                    @click="showEditDialog(scope.row.attr_id)"
                    >编辑</el-button
                  >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="deleteDialog(scope.row.attr_id)"
                    >删除</el-button
                  >
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数 -->
    <el-dialog
      :title="this.activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addDialogVisible"
      width="60%"
      @close="closeAdd"
    >
      <el-form
        ref="addRuleForm"
        :model="addForm"
        label-width="100px"
        :rules="addRules"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑修改 -->
    <el-dialog
      :title="this.activeName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editDialogVisible"
      width="60%"
    >
      <el-form
        ref="editRuleForm"
        :model="editForm"
        label-width="100px"
        :rules="editRules"
      >
        <el-form-item
          :label="this.activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除操作 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="30%">
      <span>是否删除该参数？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Parmas",
  data() {
    return {
      // 商品分类数据
      categoryList: [],
      // 指定级联选择器的配置对象
      levelProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 选中的父级分类的id数组
      selectedKeys: [],

      // 分类ID
      cateId: "",

      activeName: "many",
      // 静态参数列表
      manyList: [],
      // 静态属性列表
      onlyList: [],

      // 控制按钮与文本框的切换显示
      // inputVisible: false,
      // // 文本框的内容
      // inputValue: "",

      // 是否展示添加参数对话框
      addDialogVisible: false,

      addForm: {
        attr_name: "",
      },
      addRules: {
        attr_name: [
          {
            required: true,
            message: "名称不能为空！",
            trigger: "blur",
          },
        ],
      },

      // 参数id
      attrId: "",

      // 是否展示编辑对话框
      editDialogVisible: false,
      editForm: {
        attr_name: "",
      },
      editRules: {
        attr_name: [
          {
            required: true,
            message: "名称不能为空！",
            trigger: "blur",
          },
        ],
      },

      // 是否展示删除对话框
      delVisible: false,

      searchInput: "",
    };
  },

  created() {
    this.getCateData();
  },
  methods: {
    // 获取分类列表数据
    getCateData() {
      this.axios({
        method: "get",
        url: "categories",
        params: {
          type: 3,
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.categoryList = res.data.data;
            
          }
        })
        .catch((err) => {
          
        });
    },

    // 选项发生变化时触发
    selectCate() {
      // 
      // 获取selectedKeys数组的最后一个元素
      // let lastKey = this.selectedKeys.slice(-1);
      let lastKey = this.selectedKeys.slice(-1);
      // 
      lastKey = Number(lastKey);
      // 

      this.cateId = lastKey;
      

      this.getParamsData();
    },

    // 切换tab标签
    handleClick(tab, event) {
      // 
      
      this.getParamsData();
    },

    // 获取参数列表数据
    getParamsData() {
      this.axios({
        method: "get",
        // url:'categories/:id/attributes',
        url: `categories/${this.cateId}/attributes`,
        params: {
          sel: this.activeName,
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            res.data.data.forEach((item) => {
              // 
              // 

              //若attr_val里有空格，则按照空格进行切割
              // item.attr_val.split(/[, ]+/);

              // attr_val有可能是空，所以得判断一下它是不是空数组才能切割，否则split报错
              item.attr_vals = item.attr_vals
                ? item.attr_vals.split(/[, ]+/)
                : [];
              

              // 控制标签文本框的显示隐藏
              item.inputVisible = false;
              item.inputValue = "";
            });

            if (this.activeName === "many") {
              // 动态参数数据
              this.manyList = res.data.data;
              
            } else {
              // 静态属性数据
              this.onlyList = res.data.data;
              
            }
          }
        })
        .catch((err) => {
          
        });
    },

    // 关闭添加对话框,要重置对话框
    closeAddDialog() {
      
      this.$refs.addRuleForm.resetFields();
    },

    // 添加参数
    addParams() {
      this.$refs.addRuleForm.validate(async (valid) => {
        

        if (valid) {
          this.axios({
            method: "post",
            url: `categories/${this.cateId}/attributes`,
            data: {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            },
          })
            .then((res) => {
              
              if (res.data.meta.status == 201) {
                if (this.activeName === "many") {
                  this.$message.success("添加动态参数成功！");
                } else {
                  this.$message.success("添加静态属性成功！");
                }
                this.addDialogVisible = false;
                this.getParamsData();
                // 清除对话框
                this.addForm.attr_name = "";
              }
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },

    closeAdd(){
      this.$refs.addRuleForm.resetFields();
    },

    // 展示编辑对话框
    showEditDialog(attr_id) {
      this.editDialogVisible = true;
      
      this.attrId = attr_id;

      this.axios({
        method: "get",
        url: `categories/${this.cateId}/attributes/${this.attrId}`,
        params: {
          // attr_name: this.editForm.attr_name,
          attr_sel: this.activeName,
        },
      })
        .then((res) => {
          // 
          if (res.data.meta.status == 200) {
            this.editForm.attr_name = res.data.data.attr_name;
          }
        })
        .catch((err) => {
          
        });
    },

    // 修改参数
    editParams() {
      this.$refs.editRuleForm.validate(async (valid) => {
        

        if (valid) {
          this.axios({
            method: "put",
            url: `categories/${this.cateId}/attributes/${this.attrId}`,
            data: {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName,
            },
          })
            .then((res) => {
              
              if (res.data.meta.status == 200) {
                if (this.activeName === "many") {
                  this.$message.success("修改动态参数成功！");
                } else {
                  this.$message.success("修改静态属性成功！");
                }
                this.editDialogVisible = false;
                this.getParamsData();
                // 清除对话框
                this.editForm.attr_name = "";
              }
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },

    // 展示删除对话框
    deleteDialog(attr_id) {
      this.delVisible = true;
      
      this.attrId = attr_id;
    },

    // 删除参数
    deleteParams() {
      this.axios({
        method: "delete",
        url: `categories/${this.cateId}/attributes/${this.attrId}`,
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.$message.success("删除成功！");
            this.delVisible = false;
            this.getParamsData();
          } else {
            this.$message.error("删除失败！");
            return;
          }
        })
        .catch((err) => {
          
        });
    },

    // 点击button,显示输入框
    showInput(row) {
      // 
      row.inputVisible = true;
      this.$nextTick((_) => {
        // 自动获取文本框的焦点
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 文本框失去焦点，或按下enter就会触发
    handleInputConfirm(row) {
      // 
      
      this.attrId = row.attr_id;
      this.attrName = row.attr_name;

      // 去除空格
      if (row.inputValue.trim().length === 0) {
        (row.inputValue = ""), (row.inputVisible = false);
        return;
      }

      // 将输入的文本框内容塞进attr_vals中
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.attrVals = row.attr_vals;

      this.saveNewTag(row);
    },

    // 提交新增的标签
    saveNewTag(row) {
      this.axios({
        method: "put",
        url: `categories/${this.cateId}/attributes/${row.attr_id}`,
        data: {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          // attr_vals:this.attrVals
          attr_vals: row.attr_vals.join(" "),
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.$message.success("修改参数成功！");
          }
        })
        .catch((err) => {
          
        });
    },

    // 移除标签
    handleClose(index, row) {
      
      

      row.attr_vals.splice(index, 1);
      this.saveNewTag(row);
    },
  },
};
</script>

<style lang="less" scoped>
.params {
  margin-top: 70px;
  // background-color: #fff;
}

.box-card {
  margin-top: 22px;
  .select-box {
    // border: 1px solid #000;
    margin-top: 18px;
  }
  .el-tabs {
    // border: 1px solid #000;
    margin-top: 20px;
  }
  .el-table {
    margin-top: 16px;
    .btns {
      // border: 1px solid red;
      display: flex;
      .el-button {
        // border: 1px solid #000;
        height: 30px;
        padding-left: 10px;
        padding-right: 10px;
        display: flex;
        align-items: center;
        // margin-bottom: -20px;
        /deep/span {
          // border: 1px solid #000;
          margin-top: 0px;
        }
      }
    }
  }

}

/deep/ .el-table__expanded-cell {
  // border: 1px solid #000;
  padding-left: 50px;
  .el-tag {
    // border: 1px solid #000;
    margin-right: 8px;
    margin-bottom: 8px;
  }
  .el-input {
    width: 120px;
  }
}
</style>

<style>
.el-scrollbar {
  /* border: 1px solid red; */
  height: 200px !important;
}
</style>

